package cn.edu.cug.cs.gtl.utils.postgresql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PostgresqlUtil {
    //本地Postgresql数据库
    static String localUrl = "jdbc:postgresql:///ginventor";
    static String localName = "postgres";
    static String localPassWord = "12345678";

    //远程Postgresql数据库
    static String remoteUrl = "jdbc:postgresql://202.114.198.141/geospacex";
    static String remoteName = "gis";
    static String remotePassWord = "gis";

    private static final String DATABASE_URL = remoteUrl;
    private static final String USERNAME = remoteName;
    private static final String PASSWORD = remotePassWord;

    public Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public ResultSet executeQuery(String sql) {
        Connection connection = getConnection();
        if (connection == null) {
            return null;
        }

        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            return statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeConnection(connection);
        }
    }

}

